package com.jbit.examSystem.utils;

import com.jbit.examSystem.pojo.EmailCode;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class EmailUtil {
    private String senderEmail;//发件人邮件
    private String receiveMailAccount;//收件人邮箱
    private String authorizationCode;//授权码
    private String serverAddress;//服务器地址
    private Integer verificationCodeLength;//验证码长度

    {
        ClassLoader classLoader = EmailUtil.class.getClassLoader();
        InputStream ins = classLoader.getResourceAsStream("email.properties");
        Properties properties = new Properties();
        try {
            properties.load(ins);
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.senderEmail = properties.getProperty("senderEmail");
        this.serverAddress = properties.getProperty("serverAddress");
        this.verificationCodeLength = Integer.valueOf(properties.getProperty("verificationCodeLength"));
        this.authorizationCode = properties.getProperty("authorizationCode");
    }

    public EmailUtil(String receiveMailAccount) {
        this.receiveMailAccount = receiveMailAccount;
    }

    public EmailCode sendEmail(){
        EmailCode code = new EmailCode();
        String verificationCode = null;

        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", serverAddress);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getInstance(props);
        // 设置为debug模式, 可以查看详细的发送 log
        session.setDebug(true);

        // 3. 创建一封邮件
        MimeMessage message = null;


        verificationCode = getVerificationCode();
        code.setCode(verificationCode);

        String text = "您的验证码是：" + verificationCode + "<br/>请勿泄露验证码给他人！此验证码10分钟内有效";
        message = createMimeMessage(session, "验证码", text);


        try {
            // 4. 根据 Session 获取邮件传输对象
            Transport transport = session.getTransport();

            // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
            transport.connect(senderEmail, authorizationCode);

            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());

            Calendar calendar = Calendar.getInstance();
            int minute1 = calendar.get(Calendar.MINUTE);
            calendar.set(Calendar.MINUTE, (minute1 + 10));
            code.setExpirationTime(calendar.getTime());

            // 7. 关闭连接
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        return code;
    }

    private MimeMessage createMimeMessage(Session session, String title, String text) {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        try {
            InternetAddress[] toAddr = new InternetAddress[2];
            toAddr[0] = new InternetAddress(senderEmail, "考试系统", "UTF-8");
            toAddr[1] = new InternetAddress(receiveMailAccount, "考试系统", "UTF-8");

            message.setFrom(new InternetAddress(toAddr[0].getAddress(), "考试系统", "UTF-8"));

            // 3. To: 收件人（可以增加多个收件人、抄送、密送）
            //多方发送，给自己的邮箱也发一份,避免“554 DT:SPM”被定义为垃圾邮件
            message.setRecipients(MimeMessage.RecipientType.TO, toAddr);

            // 4. Subject: 邮件主题
            message.setSubject(title, "UTF-8");

            // 5. Content: 邮件正文（可以使用html标签）
            message.setContent(text, "text/html;charset=UTF-8");
            // 6. 设置发件时间
            message.setSentDate(new Date());

            // 7. 保存设置
            message.saveChanges();
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return message;
    }

    private String getVerificationCode(){
        String verificationCode = "";

        for (int i = 1; i <= verificationCodeLength; i++){

            int num = new Random().nextInt( 10 ) ;
            verificationCode += num;
        }
        return verificationCode;
    }

}
